<?php

class App_Methods_Request_SaveOrder {

  /**
   *
   * @var App_Methods_Data_App
   */
  public $app;
  public $order;

  public function __construct($params) {
    $this->app = new App_Methods_Data_App($params->app);
    $this->order = ($params->getDefault('order') == null) ? array() : $params->getDefault('order');
  }

  public function process() {
  	$application = ApplicationsQuery::create()
	  	->useUserPulpitQuery(null, Criteria::LEFT_JOIN)
	  	->endUse()
  		->addJoinCondition('UserPulpit', 'UserPulpit.UserId = ?', Core_Auth::getInstance()->getUser()->getId())
  		->with('UserPulpit')
  		->find();
  	$applicationArr = array();
  	foreach ($application as $application) {
  		$applicationArr[$application->getId()] = $application;
  	}
  	$con = Propel::getConnection();
  	$con->beginTransaction();
  	try {
	  	foreach ($this->order as $key => $value) {
	  		if ($applicationArr[$value]->getUserPulpits()->getFirst() instanceof UserPulpit) {
	  			$userPulpit = $applicationArr[$value]->getUserPulpits()->getFirst();
	  		}
	  		else {
	  			$userPulpit = new UserPulpit();
	  			$userPulpit->setDefaultData();
	  		}
	  		$userPulpit->setDbOrder($key);
	  		$userPulpit->save($con);
	  	}
	  	$con->commit();
  	} catch (Exception $e) {
  		$con->rollBack();
  		throw $e;
  	}
    return new App_Methods_Response_SaveOrder(true);
  }

}